package com.chen.jwt.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.Claims;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;

import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chen.jwt.entity.User;
import com.chen.jwt.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 若晨
 * @version 1.0.0
 * @ClassName JWTUtils.java
 * @Description 生成token的工具类
 * @createTime 2022年08月02日 17:54:00
 */
@Component
public class JWTUtils {


    private static UserService staticUserService;

    @Resource
    private UserService userService;

    @PostConstruct
    public void setUserService() {
        staticUserService = userService;
    }

    /**
     *生成token header.payload.signature
     * */
    private static final String SING = "123456";
    public static String getToken(Map<String,Object> map){
        //获取当前时间
        Calendar instance = Calendar.getInstance();
        //默认7天过期
        instance.add(Calendar.DATE,7);
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k,v)->{
            builder.withClaim(k, (Integer) v);
        });

        //指定令牌过期时间
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
        return token;
    }


    /**
     * 验证token合法性
     * */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SING)).build().verify(token);

    }
    /**
     * 获取当前登录的用户信息
     *
     * @return user对象
     */

    public static User getTokenInfo(String token){

        try {
            if (StrUtil.isNotBlank(token)){
                Integer id = JWT.require(Algorithm.HMAC256(SING)).build().verify(token).getClaim("id").asInt();
                return staticUserService.getById(id);
            }
        }catch (Exception e) {
            return null;
        }
        return null;
    }



    public static void main(String[] args) {


        //创建验证对象
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SING)).build();
        DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODQ2NzU4NzJ9.69krBLB6sF6b7TzYSj11jt4TpAJN-68WVHGV4zRP3bg");
        System.out.println(verify.getClaim("id").asInt());
        System.out.println(verify.getClaim("name").asString());
        //取过期时间
        System.out.println("过期时间"+verify.getExpiresAt());
    }
}
